<?php

class AdminCourseClass_Controller extends Admin_Controller {
	public function index(Request $request, Response $response) {
		$size = intval($request->size) ?: 30;
		$p = intval($request->p ?: 1);
		$from = ($p - 1) * $size;
		$q = new TrueQuery();
		if ($request->search) {
			$subQuery = new SearchQuery('name', $request->search);
			$courses = Course::find($subQuery, ['nolimit' => 1]);
			if (!$courses) $q = new Query('id', -1);
			else {
				$q = new InQuery('courseId', object_map($courses, 'id'));
			}
		}
		$data = CourseClass::find($q, ['from' => $from, 'size' => $size, 'sort' => ['created' => 'ASC']]);
		$page_nav['count'] = CourseClass::totalCount($q);
		$nav = new SubPages($size, $page_nav['count'], $p, 10, "/admin/courseClass/?p=", 2);
		$page_nav['nav'] = $nav->subPageCss2();
		$classTimes = [];
		/**
		 * @var CourseClass $courseClass
		 */
		foreach ($data as $courseClass) $classTimes[$courseClass->id] = $courseClass->classTime();
		$response->append(new View('admin/courseClass/list', compact('data', 'page_nav', 'classTimes')));
	}

	public function edit(Request $request, Response $response) {
		if (!$request->isPost()) {
			$id = $request->path(3);
			$data = CourseClass::load($id);
			if (!$id || !$data) $data = new CourseClass();
			$classTimes = array_values($data->classTime());
			$response->send(new View('admin/courseClass/edit', compact('data', 'classTimes')));
		}
		/**
		 * @var    CourseClass $data
		 */
		$data = CourseClass::createByRequest($request);
		$nullCheck = [
			'courseId' => '课程',
			'semester' => '学期',
			'capacity' => '最大容纳人数',
			'classroomId' => '教室',
			'teacherId' => '任课教师',
		];
		foreach ($nullCheck as $item => $description) if (!$data->$item) $response->alertErrorAndGoBack("{$description}不能为空！");
		$digitalCheck = [
			'capacity' => '最大容纳人数',
		];
		foreach ($digitalCheck as $item => $description) if (!is_numeric($data->$item)) $response->alertErrorAndGoBack("{$description}必须为数字！");
		//check conflict
		$classTimeCount = count($request->day);
		$teacher = $data->teacher();
		$newClassTimes = [];
		$conflictClasses = [];
		for ($i = 0; $i < $classTimeCount; $i++) {
			$classTime = new ClassTime();
			$classTime->day = $request->day[$i];
			$classTime->startTime = $request->startTimes[$i];
			$classTime->endTime = $request->endTimes[$i];
			$newClassTimes[] = $classTime;
		}
		$possibleConflictCourseClasses = CourseClass::find(new Query('teacherId', $teacher->id), ['nolimit' => 1]);
		$possibleConflictClassTimes = ClassTime::find(new InQuery('classId', object_map($possibleConflictCourseClasses, 'id' ?: [''])), ['nolimit' => 1]);
		foreach ($newClassTimes as $classTime) {
			foreach ($possibleConflictClassTimes as $possibleConflictClassTime) {
				if ($possibleConflictClassTime->day == $classTime->day) {
					if (($possibleConflictClassTime->startTime <= $classTime->startTime && $possibleConflictClassTime->endTime >= $classTime->endTime) ||
						($possibleConflictClassTime->startTime >= $classTime->startTime && $possibleConflictClassTime->startTime <= $classTime->endTime) ||
						($possibleConflictClassTime->endTime <= $classTime->endTime && $possibleConflictClassTime->endTime >= $classTime->startTime)
					) {
						$conflictClasses[] = Course::load(CourseClass::load($possibleConflictClassTime->classId)->courseId);
						continue;
					}
				}
			}
		}
		if ($conflictClasses) $response->alertAndGoBack('该教师的开课时间有冲突!\\n冲突课程:' . implode(',', object_map($conflictClasses, 'name')));
		$data->save();
		$oldTimes = ClassTime::find(new Query('classId', $data->id), ['nolimit' => 1]);
		foreach ($oldTimes as $oldTime) $oldTime->delete();
		foreach ($newClassTimes as $newTime) {
			$newTime->classId = $data->id;
			$newTime->save();
		}
		$response->alertAndGoTo('操作成功!', '/admin/CourseClass/');
	}

	public function delete(Request $request, Response $response) {
		if (!$request->path(3)) $response->alertErrorAndGoBack('请求无效！');
		/**
		 * @var CourseClass $courseClass
		 */
		$courseClass = CourseClass::load($request->path(3));
		$courseClass->remove();
		$response->alertAndGoTo('删除成功!相关记录均已删除!', '/admin/CourseClass/');
	}
}